import express from'express';
import sqlite3 from 'sqlite3';

const router = express.Router();

const db = new sqlite3.Database("./src/db/adc2.db")

//返回一天的温度数据
router.post('/temp',function(req,res){
    let {n} = req.body?req.body:{n:60*24};
    db.all(`select * from adc order by id desc limit ${n}`,[],(err,rows)=>{
        if(err){
            res.json({'err':err.message,data:null});
        }else{
            res.json({'err':null,data:rows.reverse()});
        }
    })
});


//返回最近n天的温度数据
//例如：n=0返回最近一天的温度数据
//n=1返回昨天的全部数据
//n=2返回前天的全部数据
router.post('/temp_nday',function(req,res){
    let {n} = req.body;
    let now = new Date();
    let startTime = Math.floor(now.getTime()/1000 - (n+1)*24*60*60);
    let endTime = Math.floor(now.getTime()/1000 - n*24*60*60);

    db.all(`select * from adc where time > ? and time < ? order by id desc`,
        [startTime, endTime],
        (err,rows)=>{
            if(err){
                res.json({'err':err.message,data:null});
            }else{
                res.json({'err':null,data:rows.reverse()});
            }
        }
    )
});
export default router;